<template>
  <el-tag
    v-for="tag in dynamicTags"
    :key="tag.id"
    class="mx-1"
    closable
    :disable-transitions="false"
    @close="handleClose(tag)"
  >
    {{ tag.message }}
  </el-tag>
  <el-input
    v-if="inputVisible"
    ref="InputRef"
    v-model="inputValue"
    class="ml-1 w-20"
    size="small"
    @keyup.enter="handleInputConfirm"
    @blur="handleInputConfirm"
  >
  </el-input>
  <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
    + New Tag
  </el-button>
</template>

<script lang="ts" setup>
import { ref, nextTick,watch,defineEmits } from 'vue'
import type { ElInput } from 'element-plus'
const emit = defineEmits(['updateList'])
const props = defineProps({
    list:{
        type:Array,
        default:[]
    }
})
// console.log(props.list);
const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
// 监听props上值的变化，更新到组件内部状态
watch(()=>props.list,(newVal)=>{
    dynamicTags.value = newVal
})
// 监听组件内部状态的变化，将新值传递给父组件
watch(()=>dynamicTags.value,(newVal)=>{
  emit('updateList',newVal)
},{deep:true}) // ,{deep:true} 加上deep:true,当dynamicTags数组push时，也能触发此监听的回调
const handleClose = (tag: string) => {
  dynamicTags.value = dynamicTags.value.filter(item => item.id != tag.id)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push({message:inputValue.value,id:Date.now()})
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>